﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System.Collections.Generic;
using System;
using System.IO;
using RecordPlaybackFramework;

namespace Orchard.Test.Library
{
    public class ImportExportHelper:UIHelperBase
    {
        public LiveWriterHelper LiveWriterHelper;
        public MessagesHelper MessageHelper;
        public ImportExportHelper(TestLibrary settings) : base(settings)
        {
            LiveWriterHelper = new LiveWriterHelper(settings);
            MessageHelper = new MessagesHelper(settings);
        }

        public void Import(string recipeFilePath)
        {
            selenium.Open("/Admin/ImportExport/Import");
            selenium.Type("RecipeFile", recipeFilePath);
            Submit();   
        }

        public void Export(List<string> contentTypes, bool saveMetaData, bool saveData, DataExportChoice dataExportChoice, bool saveSiteSettings)
        {
            Export(true, contentTypes, saveMetaData, saveData, dataExportChoice, saveSiteSettings);
        }

        public void Export(bool clearExportDir,List<string> contentTypes, bool saveMetaData, bool saveData, DataExportChoice dataExportChoice, bool saveSiteSettings)
        {
            //clear the export dir in App_data of Orchard.web
            if (clearExportDir)
            {
                if (Directory.Exists(TestLibrary.Consts.OrchardAppDataExportsPath))
                    Directory.Delete(TestLibrary.Consts.OrchardAppDataExportsPath, true);
            }

            selenium.Open("/Admin/ImportExport/Export");
            string contentTypesLocator = "//form[@action='/Admin/ImportExport/Export']/fieldset/ol/li";
            int contentTypesCount = (int)selenium.GetXpathCount(contentTypesLocator);
            for (int contentTypeIndex = 1; contentTypeIndex <= contentTypesCount; contentTypeIndex++)
            {
                string contentTypeName = selenium.GetText(String.Format("{0}[{1}]/label", contentTypesLocator, contentTypeIndex));
                string contentTypeCheckBox = String.Format("{0}[{1}]/input[2]", contentTypesLocator, contentTypeIndex);
                if (contentTypes != null && contentTypes.Contains(contentTypeName))
                {
                    selenium.Check(contentTypeCheckBox);
                }
                else
                {
                    selenium.Uncheck(contentTypeCheckBox);
                } 
            }
            string locatorMetaData = "//input[@id='Metadata']";
            string locatorData = "//input[@id='Data']";
            string locatorSiteSettings = "//input[@id='SiteSettings']";
            if (saveMetaData)
            {
                selenium.Check(locatorMetaData);
            }
            else
            {
                selenium.Uncheck(locatorMetaData);
            }
            if (saveData)
            {
                selenium.Check(locatorData);
                selenium.Click(Enum.GetName(typeof(DataExportChoice), dataExportChoice));
            }
            else
            {
                selenium.Uncheck(locatorData);
            }
            if (saveSiteSettings)
            {
                selenium.Check(locatorSiteSettings);
            }
            else
            {
                selenium.Uncheck(locatorSiteSettings);
            }
            selenium.Click("//button[@type='submit']");           
          
        }

        public void ConfirmExportWithRpf()  //moduleId eg:Orchard.Module.Orchard.CodeGeneration
        {            
            
            try
            {
                string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string dir = myDocumentsPath.Replace("Documents", "");
                dir = dir + "Downloads";
                try
                {
                    if (File.Exists(dir + "\\" + "export.xml"))
                        File.Delete(dir + "\\" + "export.xml");
                }
                catch(Exception ex)
                { throw ex; }
                //selenium.WaitForPopUp("_blank", "30000");
                //selenium.SelectWindow(selenium.GetAllWindowTitles()[1]);
                //selenium.SetSpeed("2000");               
                //selenium.KeyPressNative("13");
                LiveWriterHelper.InitRPF();
                string queryPopWinId = string.Format(@";Name = 'Opening export.xml' && Role = 'window'");
                ScreenElement element;

                //FireFox 3.6
                if (RPF.IsAvailable(9000, queryPopWinId))
                {
                    element = ScreenElement.FromPartialQueryId(@";Name => 'Opening export.xml';[VisibleOnly]Name = 'Save File' && Role = 'radio button'");
                    element.LeftButtonClick(1, 1);                             
                    element = ScreenElement.FromPartialQueryId(@";Name => 'Opening export.xml';[VisibleOnly]Role = 'grouping';[VisibleOnly]Name = 'Save File' && Role = 'radio button'");
                    element.LeftButtonClick(1, 1);
                    element = ScreenElement.FromPartialQueryId(@";Name => 'Opening export.xml';[VisibleOnly]Name = 'Opening export.xml' && Role = 'dialog';[VisibleOnly]Name = 'OK' && Role = 'push button'");
                    element.LeftButtonClick(10, 10);
                    
                }
                //IE 9
                queryPopWinId = (@"; ClassName => 'IEFrame';[VisibleOnly]Role = 'client' && ClassName = 'Frame Notification Bar';[VisibleOnly]Name = 'Notification bar' && Role = 'tool bar'");
                if (RPF.IsAvailable(9000, queryPopWinId))
                {
                    element = ScreenElement.FromPartialQueryId(@";ClassName => 'IEFrame';[VisibleOnly]Name = 'Notification bar' && Role = 'tool bar';[VisibleOnly]Name = 'Save' && Role = 'split button'");
                    element.LeftButtonClick(1, 1);                    
                }
                //chrome : there is no pop dialog
                //safari : unknow

            }
            catch (Exception)
            { }
            finally
            {
                LiveWriterHelper.FinishRPF();
            }

        }

        public void ConfirmExport(ref string recipeFilePath)
        {
            string exportFileName = "";
            string exportMessage = "";           

            if (MessageHelper.GetMessagesInformationItemsCount() > 0)
            {
                exportMessage = selenium.GetText("messages");
                recipeFilePath = exportMessage.Substring(exportMessage.LastIndexOf(' ') + 1);
            }
            //else   //don't care the dialog about open/download export.xml, so cancel rpf join the case
            //{                
            //    TestLibrary.ImportExportHelper.ConfirmExport();
            //    Assert.IsTrue(TestLibrary.ImportExportHelper.IsExportOk(ref recipeFilePath));
            //}
            else   //whether choose "OK" or "Cancel", the export...xml will be generated in spcial "Exports" dir
            {
                DirectoryInfo theFolder = new DirectoryInfo(TestLibrary.Consts.OrchardAppDataExportsPath);
                theFolder.Refresh();
                System.Threading.Thread.Sleep(1000);
                //FileInfo[] ss=   theFolder.GetFiles();
                foreach (FileInfo nextFile in theFolder.GetFiles("*.xml"))
                {
                    exportFileName = nextFile.Name;  //Normal, there just exist one file when 
                    break;
                }
                recipeFilePath = TestLibrary.Consts.OrchardAppDataExportsPath + "\\" + exportFileName;
            }
        }

        public bool isExportOk(string filePath)
        {
            if (File.Exists(filePath))
                return true;
            else return false;
        }

        public bool IsExportOkWithRpf(ref string returnDir)
        {

            bool result = true;
            string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string dir = myDocumentsPath.Replace("Documents", "");
            dir = dir + "Downloads";
            if (Directory.Exists(dir))
            {
                if (File.Exists(dir + "\\" + "export.xml"))
                    result = true;
                else result = false;
            }
            returnDir = dir + "\\" + "export.xml";
            return result;
        }

    }
}

public enum DataExportChoice
{
    Published,
    Draft
}
